﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;

namespace Fcbbas.CodeBuilder
{
    /// <summary>
    /// 用于序列化和反序列化的工具类
    /// </summary>
    /// <typeparam name="T">要序列化或反序列化的类</typeparam>
    public sealed class JsonSerializer<T>
    {
        /// <summary>
        /// 序列化object对象为XML字符串
        /// </summary>
        public static string Serialize(object ObjectToSerialize)
        {
            string result = null;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false));
                    xmlTextWriter.Formatting = Formatting.Indented;
                    xmlSerializer.Serialize(xmlTextWriter, ObjectToSerialize);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
                    result = uTF8Encoding.GetString(memoryStream.ToArray());
                }
            }
            catch (Exception innerException)
            {
                throw new ApplicationException("Couldn't Serialize Object:" + ObjectToSerialize.GetType().Name, innerException);
            }
            return result;
        }


        /// <summary>
        /// 将类的实例序列化为xml字符串
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string SerializeToXml(T instance)
        {
            //序列化            
            string xmlString = String.Empty;

            XmlSerializer xmlSerializer = new XmlSerializer(instance.GetType());
            MemoryStream stream = new MemoryStream();
            xmlSerializer.Serialize(stream, instance);
            byte[] buf = stream.ToArray();
            xmlString = Encoding.UTF8.GetString(buf);
            stream.Close();

            return xmlString;
        }
        /// <summary>
        /// 将xml字符串反序列化为类的实例
        /// </summary>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static T DeserializeFromXml(string xmlString)
        {
            //反序列化
            T obj = default(T);

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            byte[] buf = Encoding.ASCII.GetBytes(xmlString);
            MemoryStream stream = new MemoryStream(buf);
            obj = (T)xmlSerializer.Deserialize(stream);
            stream.Close();

            return obj;
        }

        /// <summary>
        /// 转换DataContract数据对象为json串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="value">值</param>
        /// <returns>返回DataContract数据对象的json串</returns>
        public static string DataContractToJson(T v)
        {
            MemoryStream stream1 = new MemoryStream();
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            ser.WriteObject(stream1, v);
            stream1.Position = 0;
            using (StreamReader sr = new StreamReader(stream1))
            {
                return sr.ReadToEnd();
            }
        }

        /// <summary>
        /// 转换DataContract数据对象为json串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="value">值</param>
        /// <returns>返回DataContract数据对象的json串</returns>
        public static T JsonToDataContract(string value)
        {
            //反序列化
            T obj = default(T);

            DataContractJsonSerializer xmlSerializer = new DataContractJsonSerializer(typeof(T));
            byte[] buf = Encoding.Unicode.GetBytes(value);
            MemoryStream stream = new MemoryStream(buf);
            obj = (T)xmlSerializer.ReadObject(stream);
            stream.Close();

            return obj;
        }


        /// <summary>
        /// 将JSON数据格转换实体对象。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T JSonToObject<T>(string strJson)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            T t = default(T);
            try
            {
                t = jss.Deserialize<T>(strJson);
            }
            catch
            {

            }
            if (t == null)
            {
                try
                {
                    t = Activator.CreateInstance<T>();
                    //t = (T)JSONtoOject(t, strJson);
                }
                catch { }
            }
            if (t != null)
            {
                return t;
            }
            else
            {
                return default(T);
                //return Activator.CreateInstance<T>();
            }
        }
    }
}
